﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using TestResultsLogging.Models;

using log4net;


namespace TestResultsLogging.Controllers
{
    public class HomeController : Controller
    {

        private TestCaseDBInteraction _db = new TestCaseDBInteraction();
        private TestResultsDBEntities _entities = new TestResultsDBEntities();
        private DateTime dt = new DateTime(1900, 1, 1);
        private ILog log = LogManager.GetLogger(typeof(HomeController));
        
        //
        // GET: /Home/

        public ActionResult Index()
        {
            try
            {
                log.Debug("Entering HomeController.Index; " + this.ToString());
                return View(_entities.TestResults_vw.ToList());
            }
            catch (Exception e)
            {
                log.Error("Exception", e);
                ViewData["message"] = "Exception: " + e.Message;
                return View("Error");
            }
        }

        //
        // GET: /Home/Details/5

        public ActionResult Details(int id)
        {
            try
            {
                log.Debug("Entering HomeController.Details; " + this.ToString());
                var individualResults = (from t in _entities.TestResults_vw
                                         where t.TestRunResultsId_pk == id
                                         select t).First();

                return View(individualResults);
            }

            catch (Exception e)
            {
                log.Error("Exception", e);
                ViewData["message"] = "Exception: " + e.Message;
                return View("Error");
            }
        }

        //
        // GET: /Home/Create

        public ActionResult Create()
        {
            //Setting this to return an error message for the client
            log.Debug("Entering HomeController.Create; " + this.ToString());
            ViewData["message"] = "Create requires parameters";
            return View("Error");
        } 

        //
        // POST: /Home/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create([Bind (Exclude = "TestRunResultsId_pk, CreatedDateTime, CreatedBy, ModifiedDateTime, ModifiedBy")] TestRunResults_tbl testrunToCreate)
        {
            try
            {
                log.Debug("Entering HomeController.Create; " + this.ToString());
                // Make sure test case is valid
                bool testcaseExists;
                testcaseExists = _db.testCaseExists(testrunToCreate.TestCaseId_fk);
                if (!testcaseExists)
                {
                    ViewData["message"] = "Test Case " + testrunToCreate.TestCaseId_fk + " is invalid";
                    return View("Error");
                }

                //Make sure it is a valid status
                bool testStatusValid;
                testStatusValid = _db.testStatusValid(testrunToCreate.TestCaseStatusId_fk);
                if (!testStatusValid)
                {
                    ViewData["message"] = "Test Status " + testrunToCreate.TestCaseStatusId_fk + " is invalid";
                    return View("Error");
                }

                // Account for null End DateTime
                if (testrunToCreate.EndedTestRun == null)
                {
                    testrunToCreate.EndedTestRun = dt;
                }

                int success = _db.insertTestRun(testrunToCreate);

                if (success < 1)
                {
                    ViewData["message"] = "Test Run insertion failed";
                    return View("Error");
                }

                int returnTestRun = _db.retrieveLastTestRun(testrunToCreate.TestCaseId_fk);

                if (returnTestRun < 1)
                {
                    ViewData["message"] = "Cannot find inserted test run";
                    return View("Error");
                }

                ViewData["message"] = "Created Test Run: " + returnTestRun.ToString();
                return View("Created");

            }
            catch(Exception e)
            {
                ViewData["message"] = "Exception: " + e.Message;
                return View("Error");
            }
        }
        
        //
        // GET: /Home/Edit/5
 
        public ActionResult Edit(int id)
        {
            //Disabling this to remove the ability to edit w/out a full object
            //Leaving it in in case there is some reason we need to edit this way in the future
            log.Debug("Entering HomeController.Edit; " + this.ToString());
            string msg = "Editing requires more than one parameter";
            log.Error(msg);
            ViewData["message"] = msg;
            return View("Error");
        }

        //
        // POST: /Home/Edit/5

        [AcceptVerbs(HttpVerbs.Post)] 
        public ActionResult Edit(UpdatedTestRun testRunToUpdate)
        {
            try
            {
                log.Debug("Entering HomeController.Edit with testRunToUpdate; " + this.ToString());
                //Check for test run
                bool testRunExists;
                testRunExists = _db.testRunValid(testRunToUpdate.TestRunId);
                if (!testRunExists)
                {
                    string msg = testRunToUpdate.TestRunId + " is an invalid Test Run"; 
                    log.Error(msg);
                    ViewData["message"] = msg;
                    return View("Error");
                }

                //Make sure it is a valid status
                bool testStatusValid;
                testStatusValid = _db.testStatusValid(testRunToUpdate.TestCaseStatusId);
                if (!testStatusValid)
                {
                    string msg = testRunToUpdate.TestCaseStatusId + " is an invalid Test Status Id";
                    log.Error(msg);
                    ViewData["message"] = msg;
                    return View("Error");
                }

                // Account for null End DateTime
                if (testRunToUpdate.EndedTestRun == null)
                {
                    testRunToUpdate.EndedTestRun = dt;
                    log.Info("EndDateTime was null; changed to " + dt);
                }

                int success = _db.updateTestRun(testRunToUpdate);
                if (success != 1)
                {
                    string msg = "Update failed, Error Code: " + success.ToString();
                    log.Error(msg);
                    ViewData["message"] = msg;
                    return View("Error");
                }

                log.Info("Record updated successfully");
                ViewData["message"] = "Success";
                return View("Updated");
            }
            catch(Exception e)
            {
                log.Error("Exception", e);
                ViewData["message"] = "Exception " + e.Message;
                return View("Error");
            }
        }

        //
        // GET: /Home/Delete/5
 
        public ActionResult Delete(int id)
        {
            log.Debug("Entering HomeController.Delete; " + this.ToString());
            ViewData["message"] = "Delete not implemented";
            return View("Error");
        }

        //
        // POST: /Home/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                log.Debug("Entering HomeController.Delete; " + this.ToString());
                ViewData["message"] = "Delete not implemented";
                return View("Error");
            }
            catch(Exception e)
            {
                log.Error("Exception", e);
                ViewData["message"] = "Exception: " + e.Message;
                return View("Error");
            }
        }
    }
}
